﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TrayMes
{
    public class GetEnumDescription
    {
        public static T GetDescriptionByEnum<T>(Enum value) where T : Attribute, new()
        {
            string val = value.ToString();
            System.Reflection.FieldInfo fieldInfo = value.GetType().GetField(val);
            object[] objects = fieldInfo.GetCustomAttributes(typeof(T), false);
            if (objects.Length == 0)
            {
                return new T();
            }
            T descriptionAttribute = (T)objects[0];
            return descriptionAttribute;
        }
        public static T GetEnumByDesceiption<T>(T attr) where T : Attribute, new()
        {
            System.Reflection.FieldInfo[] fields = typeof(T).GetFields();
            foreach (System.Reflection.FieldInfo fieldInfo in fields)
            {
                object[] objects = fieldInfo.GetCustomAttributes(typeof(T), false);
                if (objects.Length > 0 && (objects[0] as T).Equals(attr))
                {
                    return (T)fieldInfo.GetValue(null);
                }
            }
            throw new ArgumentException($"{attr} 未能找到对应的枚举", "Description");
        }
    }
}
